A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. Promises provide a cleaner, more flexible way to handle asynchronous operations compared to callbacks.
You can create a promise using the Promise
constructor:
let myPromise = new Promise(function(resolve, reject) {
// Producing code (may take some time)
let success = true; // Simulating success or failure
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed.");
}
});
You can consume a promise using the then
and catch
methods:
myPromise.then(function(value) {
console.log(value); // "Operation was successful!"
}).catch(function(error) {
console.log(error); // "Operation failed."
});
Promises can be chained to handle multiple asynchronous operations in sequence:
let promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(10);
}, 1000);
});
promise.then(function(value) {
console.log(value); // 10
return value * 2;
}).then(function(value) {
console.log(value); // 20
return value * 3;
}).then(function(value) {
console.log(value); // 60
}).catch(function(error) {
console.log(error);
});
A promise can be in one of three states:
Here is an example demonstrating how to access and manipulate child elements:
// HTML
//
// Child 1
// Child 2
//
let parent = document.getElementById('parent');
let children = parent.getElementsByClassName('child');
for (let i = 0; i < children.length; i++) {
children[i].style.color = 'blue';
}
For more detailed information, you can check out resources like W3Schools[^1^][1] and MDN Web Docs[^2^][2].